<?php
    /*********************************************************************************
     * Zurmo is a customer relationship management program developed by
     * Zurmo, Inc. Copyright (C) 2014 Zurmo Inc.
     *
     * Zurmo is free software; you can redistribute it and/or modify it under
     * the terms of the GNU Affero General Public License version 3 as published by the
     * Free Software Foundation with the addition of the following permission added
     * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
     * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
     * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
     *
     * Zurmo is distributed in the hope that it will be useful, but WITHOUT
     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
     * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
     * details.
     *
     * You should have received a copy of the GNU Affero General Public License along with
     * this program; if not, see http://www.gnu.org/licenses or write to the Free
     * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
     * 02110-1301 USA.
     *
     * You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive
     * Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com.
     *
     * The interactive user interfaces in original and modified versions
     * of this program must display Appropriate Legal Notices, as required under
     * Section 5 of the GNU Affero General Public License version 3.
     *
     * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
     * these Appropriate Legal Notices must retain the display of the Zurmo
     * logo and Zurmo copyright notice. If the display of the logo is not reasonably
     * feasible for technical reasons, the Appropriate Legal Notices must display the words
     * "Copyright Zurmo Inc. 2014. All rights reserved".
     ********************************************************************************/

    /**
     * Model for storing currency attribute values on other models.
     */
    class CurrencyValue extends OwnedModel
    {
        protected function constructDerived($bean, $setDefaults)
        {
            assert('$bean === null || $bean instanceof RedBean_OODBBean');
            assert('is_bool($setDefaults)');
            parent::constructDerived($bean, $setDefaults);
            if ($bean ===  null && $setDefaults)
            {
                $currentUser = Yii::app()->user->userModel;
                if (!$currentUser instanceof User)
                {
                    throw new NoCurrentUserSecurityException();
                }
                $this->currency = Yii::app()->currencyHelper->getActiveCurrencyForCurrentUser();
            }
        }

        public function __toString()
        {
            if (trim($this->value) == '')
            {
                return Zurmo::t('Core', '(None)');
            }
            return strval($this->value);
        }

        public static function getDefaultMetadata()
        {
            $metadata = parent::getDefaultMetadata();
            $metadata[__CLASS__] = array(
                'members' => array(
                    'rateToBase',
                    'value',
                ),
                'relations' => array(
                    'currency' => array(static::HAS_ONE, 'Currency'),
                ),
                'rules' => array(
                    array('currency',    'required'),
                    array('rateToBase',  'required'),
                    array('rateToBase',  'type', 'type' => 'float'),
                    array('value',       'required'),
                    array('value',       'type',    'type' => 'float'),
                    array('value',       'default', 'value' => 0),
                    array('value',       'numerical',  'min' => 0, 'on' => 'positiveValue'),
                ),
                'defaultSortAttribute' => 'value'
            );
            return $metadata;
        }

        public static function isTypeDeletable()
        {
            return true;
        }

        /**
         * Given an id of a currency model, determine if any currency values are using this currency.
         * @return true if at least one currency value model is using this currency.
         * @param integer $currencyId
         */
        public static function isCurrencyInUseById($currencyId)
        {
            assert('is_int($currencyId)');
            $columnName = static::getForeignKeyName('CurrencyValue', 'currency');
            $quote      = DatabaseCompatibilityUtil::getQuote();
            $where      = "{$quote}{$columnName}{$quote} = '{$currencyId}'";
            $count      = CurrencyValue::getCount(null, $where);
            if ($count > 0)
            {
                return true;
            }
            return false;
        }

        /**
         * Get the rateToBase from the currency model. If the scenario is importModel, then having a rateToBase
         * manually set is ok.
         * @return true to signal success and that validate can proceed.
         */
        public function beforeValidate()
        {
            if (!parent::beforeValidate())
            {
                return false;
            }
            if ($this->currency->rateToBase !== null &&
                ($this->rateToBase === null                     ||
                 array_key_exists('value', $this->originalAttributeValues) ||
                 array_key_exists('currency', $this->originalAttributeValues)) &&
                !($this->getScenario() == 'importModel' && $this->rateToBase != null))
            {
                $this->rateToBase = $this->currency->rateToBase;
                assert('$this->rateToBase !== null');
            }
            return true;
        }

        protected static function translatedAttributeLabels($language)
        {
            return array_merge(parent::translatedAttributeLabels($language),
                array(
                    'currency'      => Zurmo::t('ZurmoModule', 'Currency',      array(), null, $language),
                    'rateToBase'    => Zurmo::t('ZurmoModule', 'Rate To Base',  array(), null, $language),
                    'value'         => Zurmo::t('Core',        'Value',         array(), null, $language),
                )
            );
        }
    }
?>
